package com.whjk.system.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whjk.core.security.uitls.SecurityUtils;
import com.whjk.system.biz.mapper.WhjkPackageRelMapper;
import com.whjk.system.biz.mapper.WhjkZdmxMapper;
import com.whjk.system.biz.service.*;
import com.whjk.system.data.dto.StatisticsDto;
import com.whjk.system.data.dto.WhjkPackageRelDto;
import com.whjk.system.data.dto.WhjkPackageRelInfoDto;
import com.whjk.system.data.dto.WhjkZdmxDto;
import com.whjk.system.data.entity.*;
import com.whjk.system.data.po.WhjkPackageRelPo;
import com.whjk.system.data.uitls.NumberUtils;
import com.whjk.system.data.vo.PackageRelCountVo;
import com.whjk.system.data.vo.ReviewVo;
import com.whjk.system.data.vo.ZdXjVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 体检登记项目明细关联表 服务实现类
 * </p>
 *
 * @author hl
 * @since 2023-06-28
 */
@Service
public class WhjkPackageRelServiceImpl extends ServiceImpl<WhjkPackageRelMapper, WhjkPackageRel> implements WhjkPackageRelService {
    @Autowired
    WhjkZhxmService zhxmService;
    @Autowired
    WhjkPackageRelInfoService packageRelInfoService;
    @Autowired
    WhjkZdmxService zdmxService;
    @Autowired
    WhjkZdjywhService zdjywhService;
    @Autowired
    WhjkPersonService personService;
    @Autowired
    WhjkCjjgwhService cjjgwhService;
    @Autowired
    WhjkZdjywhInfoService zdjywhInfoService;
    @Autowired
    WhjkZdmxMapper zdmxMapper;

    @Override
    public List<WhjkPackageRelPo> selectByCheckStatus(QueryWrapper<Object> eq) {
        return baseMapper.selectByCheckStatus(eq);
    }

    /**
     * 生成小结
     *
     * @param packageRelDto
     */
    @Override
    public ZdXjVo generateSection(WhjkPackageRelDto packageRelDto) {
        ZdXjVo zdXjVo = new ZdXjVo();
        StringBuilder builder = new StringBuilder();
        //查询项目
        WhjkZhxm zhxm = zhxmService.getById(packageRelDto.getXmId());
        List<WhjkPackageRelInfoDto> packageRelInfoList = packageRelDto.getPackageRelInfoList();
        //医生检查项目
        if (zhxm.getJclx().equals("1")) {

        }
        //lis检查项目
        if (zhxm.getJclx().equals("2")) {
            packageRelInfoList.forEach(f -> {
                //判断上限，下限，以及值是否是数字。如果都是判断是否偏高偏低
                //1正常2偏高3偏低
                Integer range = NumberUtils.range(f.getCheckResult(), f.getSzxx(), f.getSzsx());
                if (range != 1) {
                    f.setIsAbnormal(range);
                } else {
                    f.setIsAbnormal(0);
                }
                //判断那些是异常项目
                if (f.getIsAbnormal() != 0) {
                    builder.append(f.getJcxmName()).append(":").append(f.getCheckResult()).append(" ");
                    if (StringUtils.isNotBlank(f.getDw())) builder.append(f.getDw());
                    String is_abnormal = "";
                    if (f.getIsAbnormal() == 1) {
                        is_abnormal = "不正常";
                    } else if (f.getIsAbnormal() == 2) {
                        is_abnormal = "偏高";
                    } else if (f.getIsAbnormal() == 3) {
                        is_abnormal = "偏低";
                    } else if (f.getIsAbnormal() == 4) {
                        is_abnormal = "高于极限";
                    } else if (f.getIsAbnormal() == 5) {
                        is_abnormal = "低于极限";
                    } else if (f.getIsAbnormal() == 6) {
                        is_abnormal = "高";
                    } else if (f.getIsAbnormal() == 7) {
                        is_abnormal = "低";
                    }
                    builder.append(is_abnormal).append("\n");
                }
            });
            if (builder.length() == 0) {
                zdXjVo.setConclusion("未发现明显异常");
            } else {
                zdXjVo.setConclusion(builder.toString());
            }
        }
        //pacs功能项目
        if (zhxm.getJclx().equals("3")) {

        }
        //诊断结果
        zdXjVo.setZdjgList(zdjywhService.getZdResult(packageRelDto));
        return zdXjVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveResults(WhjkPackageRelDto packageRelDto) {
        //保存子项
        List<WhjkPackageRelInfoDto> packageRelInfoList = packageRelDto.getPackageRelInfoList();
        List<WhjkPackageRelInfo> collect = packageRelInfoList.stream().map(f -> {
            WhjkPackageRelInfo whjkPackageRelInfo = new WhjkPackageRelInfo();
            BeanUtils.copyProperties(f, whjkPackageRelInfo);
            //判断上限，下限，以及值是否是数字。如果都是判断是否偏高偏低
            //1正常2偏高3偏低
            Integer range = NumberUtils.range(whjkPackageRelInfo.getCheckResult(), f.getSzxx(), f.getSzsx());
            if (range != 1) {
                whjkPackageRelInfo.setIsAbnormal(range);
            } else {
                whjkPackageRelInfo.setIsAbnormal(0);
            }
            //如果是选择的常见结果
            if (StringUtils.isNotEmpty(f.getJgId())){
                WhjkCjjgwh cjjg = cjjgwhService.getById(f.getJgId());
                whjkPackageRelInfo.setIsPositive(Integer.valueOf(cjjg.getSfyx()));
            }
            return whjkPackageRelInfo;
        }).collect(Collectors.toList());
        packageRelInfoService.updateBatchById(collect);
        //保存小节
        WhjkPackageRel packageRel = this.getById(packageRelDto.getId());
        packageRel.setCheckStatus("1");
        packageRel.setSummarize(packageRelDto.getSummarize());
        packageRel.setCheckPart(packageRelDto.getCheckPart());
        packageRel.setAuxiliaraResult(packageRelDto.getAuxiliaraResult());
        if (StringUtils.isBlank(packageRel.getCheckDoctor())) {
            packageRel.setCheckDoctor(SecurityUtils.getUser().getName());
            packageRel.setCheckTime(LocalDateTime.now());
        }
        this.updateById(packageRel);
        //保存诊断
        List<WhjkZdmxDto> zdjywhDtoList = packageRelDto.getZdmxList();
        List<WhjkZdmx> list = zdmxService.list(new LambdaQueryWrapper<WhjkZdmx>()
                .eq(WhjkZdmx::getPeId, packageRelDto.getPeId())
                .eq(WhjkZdmx::getRelId, packageRelDto.getId())
                .eq(WhjkZdmx::getDelFlag, 0));
        //过滤掉被删了
        List<String> collect1 = list.stream().map(WhjkZdmx::getId).collect(Collectors.toList());
        List<String> collect2 = zdjywhDtoList.stream().map(WhjkZdmx::getId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        //取差集
        List<String> collect3 = new ArrayList<>(CollectionUtils.subtract(collect1, collect2));
        if (collect3.size() > 0) {
            zdmxService.update(WhjkZdmx.builder().delFlag("1").build(), new LambdaQueryWrapper<WhjkZdmx>()
                    .in(WhjkZdmx::getId, collect3));
        }
        List<WhjkZdmx> zdmxList = zdjywhDtoList.stream().map(f -> {
            WhjkZdmx zdmx = new WhjkZdmx();
            BeanUtils.copyProperties(f, zdmx);
            zdmx.setPeId(packageRel.getPeId());
            zdmx.setRelId(packageRel.getId());
            zdmx.setZhxmId(packageRel.getXmId());
            return zdmx;
        }).collect(Collectors.toList());
        zdmxService.saveOrUpdateBatch(zdmxList);
        //判断是否全部体检完成，如果全部体检完成进行下一阶段
        int count = this.count(new LambdaQueryWrapper<WhjkPackageRel>()
                .eq(WhjkPackageRel::getPeId, packageRelDto.getPeId())
                .eq(WhjkPackageRel::getDelFlag, 0)
                .eq(WhjkPackageRel::getCheckStatus, 0));
        if (count == 0) {
            WhjkPerson person = personService.getById(packageRelDto.getPeId());
            if(person.getProcess().equals("2")){
                personService.updateById(WhjkPerson.builder().id(packageRelDto.getPeId()).process("3").build());
            }
        }
    }


    @Override
    public Page<PackageRelCountVo> countDoctors(Page<Object> Page, StatisticsDto statisticsDto) {
        return baseMapper.selectCountByDoctors(new Page<>(statisticsDto.getCurrent(), statisticsDto.getSize()), new QueryWrapper<>()
                .eq("t1.del_flag", 0)
                .eq("t1.check_status", 1)
                .apply(StringUtils.isNotBlank(statisticsDto.getPeDate()), "date_format(t1.pe_date,'%Y-%m-%d')='" + statisticsDto.getPeDate() + "'")
                .groupBy("t1.check_doctor", "t1.xm_id"));

    }

    @Override
    public List<WhjkPerson> ProjectPersonDetails(StatisticsDto statisticsDto) {
        return baseMapper.SelectPersonDetails(new QueryWrapper<WhjkPerson>()
                .eq("t1.del_flag", 0)
                .eq("t1.check_status", 1)
                .eq("t1.check_doctor", statisticsDto.getCheckDoctor())
                .eq("t1.xm_id", statisticsDto.getXmId())
                .apply(StringUtils.isNotBlank(statisticsDto.getPeDate()), "date_format(t2.pe_date,'%Y-%m-%d')='" + statisticsDto.getPeDate() + "'")

        );

    }


    @Override
    public List<ReviewVo> getReviewList(String peId) {
        //所有建议
        List<WhjkZdjywhInfo> infoList = zdjywhInfoService.list(
                new LambdaQueryWrapper<WhjkZdjywhInfo>().eq(WhjkZdjywhInfo::getDelFlag, 0)
        );
        //诊断列表以及建议
        List<WhjkZdmxDto> zdmxDtoList = zdmxMapper.selectRelZdmx(new QueryWrapper<>()
                .eq("wz.pe_id", peId)
                .eq("wz.del_flag", 0)
                .eq("zhxm.del_flag", 0)
                .eq("ks.del_flag", 0)
                .eq("wpr.del_flag", 0))
                .stream().map(m -> {
                    WhjkZdmxDto zdmxDto = new WhjkZdmxDto();
                    BeanUtils.copyProperties(m, zdmxDto);
                    zdmxDto.setInfoList(
                            infoList.stream().filter(f -> f.getZdjyId().equals(zdmxDto.getZdjywhId()))
                                    .collect(Collectors.toList())
                    );
                    return zdmxDto;
                }).collect(Collectors.toList());
        //组合名称 小结 诊断建议
        List<ReviewVo> reviewList = this.baseMapper.getReviewList(peId);
        return reviewList.stream().map(m -> {
                    ReviewVo reviewVo = new ReviewVo();
                    BeanUtils.copyProperties(m,reviewVo);
                    reviewVo.setZdmxDtoList(
                            zdmxDtoList.stream().filter(f -> f.getRelId().equals(m.getId()))
                                    .collect(Collectors.toList())
                    );
                    return reviewVo;
        }).collect(Collectors.toList());
    }
}
